<?php

namespace App\Logic;

class WxPayDataLogic
{

    protected function _initialize() 
    {
        parent::_initialize();

        if (!defined('IN_ECS'))
		{
		    die('Hacking attempt');
		}

    }	
 	protected $KEY = 'ed6e318771f4db54117aff7a6b1c4ff4';

	/**
	 * 设置签名，详见签名生成算法
	 * @param string $value
	**/
	public function SetSign($data)
	{
		$sign = $this->MakeSign($data);
		$data['sign'] = $sign;
		return $data;
	}

	/**
	 * 生成签名
	 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
	 */
	public function MakeSign($data=array())
	{
	
		//签名步骤一：按字典序排序参数
		
		ksort($data);
		
		$string='';
		
		foreach($data as $k=>$item)
		{
			if( $item !='' )
			{
				$string.= $k.'='.$item.'&';
			}
		}
		
		$string = rtrim($string, "&");
		
		//签名步骤二：在string后加入KEY
		
		$string = $string . "&key=".$this->KEY;
		
		//签名步骤三：加密
		$string = md5($string);
		
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		
		return $result;
	}
	
	public function CheckSign($data=array(),$sign='')
	{
		unset($data['sign']);
		
		if($this->MakeSign($data) == $sign)
		{
			return true;
		}
		return false;
	}
	
	/**
	 * 输出xml字符
	 * @throws WxPayException
	 **/
	public function ToXml($data)
	{
		$xml = "<xml>";
		foreach ($data as $key=>$val)
		{
			if (is_numeric($val))
			{
				$xml.="<".$key.">".$val."</".$key.">";
			}else{
				$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			}
		}
		$xml.="</xml>";
		return $xml;
	}

	/**
	 * 将xml转为array
	 * @param string $xml
	 * @throws WxPayException
	 */
	public function FromXml($xml)
	{
		if(!$xml){
			return array('return_code' => 'FAIL','return_msg'=>'xml异常');
		}
		//将XML转为array
		//禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		return array('return_code' => 'SUCCESS','data'=>$data);
	}
	/**
	 * 
	 * 回复通知
	 * @param bool $needSign 是否需要签名输出
	 */
	public function ReplyNotify($data=array(),$needSign = true)
	{
		//如果需要签名
		if($needSign == true)
		{
			$data = $this->SetSign($data);
		}
		return $this->ToXml($data);
	}

}

?>